(function ($) {

function addScript(scriptURL, onload) {
   var script = document.createElement('script');
   script.setAttribute("type", "application/javascript");
   script.setAttribute("src", scriptURL);
   if (onload) script.onload = onload;
   document.documentElement.appendChild(script);
}

function addDrawerScript(){
    addScript("http://127.0.0.1:3000/javascripts/drawer.js");
}

function injectDrawer(creds) {
  
  console.log("Inject drawer with credentials:", creds);
  injectCredentials(creds);
  
  $.get("http://127.0.0.1:3000/api/drawer")
  .done(function(data){

    $('body').append(data);

    //addScript("http://127.0.0.1:3000/javascripts/drawer.js");
    addScript(chrome.extension.getURL("lib/underscore.js"), addDrawerScript);

  })
  .fail(function(res) {
    console.log("Unable to load drawer: ", res);

    // TODO: Decide what should be done on this error
    
    // if (res.status == 401) {
    //   console.log("No logged api user");
    //   $.get('http://127.0.0.1:3000/loggedin', function(resp) {
    //     console.log("Checking if web loggedin: ", resp);
    //   });
            
    // }
    
  });
}

function injectCredentials(creds) {
  console.log("Inject credentials", creds);
  if (creds) {
    var inject = ['var sz_user_guid = "'    +creds.user_guid    + '"',
                  'var sz_access_token = "' +creds.access_token + '"',
                  'var sz_username = "'     +creds.username     + '"'].join('\n');

  }
  else {
    var inject = 'var sz_login_url = "'  +chrome.extension.getURL("options.html") + '"\n'
  }
    
  var script = document.createElement('script');
  script.textContent = inject;
  (document.head||document.documentElement).appendChild(script);
  script.parentNode.removeChild(script);
  
}

function generateCredentials(callback) {
  console.log("Check if we have valid session");
  $.get('http://127.0.0.1:3000/api/login')
  .done(function(data) {
    console.log("Got valid session, got creds: ", data);
    callback({
      user_guid : data.user_guid, 
      access_token : data.access_token,
      username : data.username
    });
  })
  .fail(function(res) {
    console.log("No valid session, no creds:", res);
    callback(null);
  });
}

function getCredentials(callback) {
  chrome.storage.local.get(['user_guid', 'access_token', 'username'], function(creds) {
    console.log(creds);
    if (creds.user_guid && creds.access_token) {
      console.log("Creds loaded from chrome.store: \n", creds);
      $.get('http://127.0.0.1:3000/api/loggedin?user_guid='+creds.user_guid+'&access_token='+creds.access_token)
      .done(function(data) {
        console.log("Creds valid: \n", creds);
        callback(creds);
      })
      .fail(function(res) {
        if (res.status == 401) {
          console.log("Invalid creds, generating new ones: \n", creds);
          var creds = generateCredentials(callback);
        }
      });
    }
    else
    {
      console.log("No creds in chrome.storage");
      generateCredentials(callback);
    }
  });
}

console.log("Sharez Extension Running!");

chrome.extension.sendMessage({enabled: "enabled"}, function(response) {
  if(window.location.href.indexOf('127.0.0.1') == -1 && response.enabled == "true")
  { 
    console.log("ShareZ Enabled: injecting drawer");

    $('head').append( $('<link rel="stylesheet" type="text/css" />')
      .attr('href', 'http://127.0.0.1:3000/stylesheets/drawer.css')
      .load(function() {

        getCredentials(injectDrawer);

      })
    );
  }
});    

})(window.jQuery); 